package dk.kmd.statemachine.eugenia.validation.popup.actions;

import java.io.File;

import org.eclipse.core.resources.IResource;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;

import statemachine.Statemachine;
import statemachine.StatemachinePackage;

public class ExportToJavaPopupAction implements IObjectActionDelegate {

	private Shell shell;

	/**
	 * Constructor for Action1.
	 */
	public ExportToJavaPopupAction() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		ISelection selection = PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getSelectionService()
				.getSelection();
		if (selection instanceof IStructuredSelection) {
			IStructuredSelection structuredSelection = (IStructuredSelection) selection;
			Object element = structuredSelection.getFirstElement();
			if (element instanceof IResource) {
				IResource file = (IResource) element;

				File javaFile = file.getRawLocation().toFile();

				ResourceSet resourceSet = new ResourceSetImpl();

				// Register the appropriate resource factory to handle all file
				// extensions.
				//
				resourceSet
						.getResourceFactoryRegistry()
						.getExtensionToFactoryMap()
						.put(Resource.Factory.Registry.DEFAULT_EXTENSION,
								new XMIResourceFactoryImpl());

				// Register the package to ensure it is available during
				// loading.
				//
				resourceSet.getPackageRegistry().put(
						StatemachinePackage.eNS_URI,
						StatemachinePackage.eINSTANCE);

				Resource resource = resourceSet.getResource(
						URI.createFileURI(javaFile.getAbsolutePath()), true);

				Statemachine st = (Statemachine) resource.getContents().get(0);

			}

		}

		MessageDialog.openInformation(shell, "Export",
				"Export to Java was executed.");
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
	}

}
